import * as step from '@flow-step/step-toolkit'

const FLOW_JOB_TOKEN: string = 'FLOW_JOB_TOKEN'

export async function getJenkinsCertificate() {
    const serviceConnectionId = process.env['SERVICE_CONNECTION_ID']
    if (serviceConnectionId == undefined) {
        throw new Error('missing SERVICE_CONNECTION_ID')
    }

    const flowJobToken: string | undefined =
        process.env[FLOW_JOB_TOKEN]

    if (flowJobToken == undefined) {
        throw new Error('missing FLOW_JOB_TOKEN')
    }

    const jenkinsCertificate = await step.certificate.getJenkinsCertificate(flowJobToken, serviceConnectionId as string)
    if (jenkinsCertificate === undefined || jenkinsCertificate.jenkinsMaster === '') {
        throw new Error(`get JenkinsCertificate but error: ${JSON.stringify(jenkinsCertificate)}`)
    }

    step.debug(`get JenkinsCertificate data: ${JSON.stringify(jenkinsCertificate)}`)
    return Promise.resolve(jenkinsCertificate)
}